package com.controller;

import com.entity.Teacher;
import com.util.DataSourceUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/teachers")
public class GetTeacherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Teacher teacher = null;
        String sql = "select * from teachers where id=?";
        try (Connection conn = DataSourceUtils.getConnection();
            PreparedStatement st = conn.prepareStatement(sql)) {
            st.setString(1, req.getParameter("tid"));
            try (ResultSet rs = st.executeQuery()) {
                while (rs.next()) {
                    teacher = new Teacher();
                    teacher.setId(rs.getInt("id"));
                    teacher.setName(rs.getString("name"));
                    teacher.setGrade(rs.getString("grade"));
                    teacher.setImage(rs.getString("img"));
                    teacher.setIntroduction(rs.getString("intro"));
                }
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        req.setAttribute("teacher", teacher);
        req.getRequestDispatcher("/WEB-INF/teachers/queryt.jsp").forward(req, resp);
    }
}
